package comi.example.xiong.bearfruit.Login;


import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;


import com.example.softdk.ycshop.R;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import comi.example.xiong.bearfruit.MainActivity2;
import comi.example.xiong.bearfruit.base.BaseActivity;
import comi.example.xiong.bearfruit.base.RequestInterface;
import comi.example.xiong.bearfruit.base.ServerResponse;
import comi.example.xiong.bearfruit.bean.User;
import comi.example.xiong.bearfruit.my.UpdateUserInfoActivity;
import comi.example.xiong.bearfruit.utils.SharedPreferenceUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.cb_loginInfo)
    CheckBox cbLoginInfo;
    @BindView(R.id.cb_autoLogin)
    CheckBox cbAutoLogin;

    @Override
    public int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

    }

    @Override
    public void initData() {
        String accountStr = (String) SharedPreferenceUtil.get(this, "account", ""/*这儿不能放null，因为辅助类中取值的时候会根据这的值的类型取对应类型的值，之前问题就出在这里*/);
        String passwordStr = (String) SharedPreferenceUtil.get(this, "password", "");
        boolean loginInfo = (boolean) SharedPreferenceUtil.get(this, "loginInfo", false);
        boolean autoLogin = (boolean) SharedPreferenceUtil.get(this, "autoLogin", false);

        cbLoginInfo.setChecked(loginInfo);
        cbAutoLogin.setChecked(autoLogin);
        if (loginInfo) {
            etAccount.setText(accountStr);
            etPassword.setText(passwordStr);
        }
        if (autoLogin) {
            if (TextUtils.isEmpty(accountStr)) {
                toastShort("账号不能为空！");
                return;
            }
            if (TextUtils.isEmpty(passwordStr)) {
                toastShort("密码不能为空！");
                return;
            }
            doLogin(accountStr, passwordStr);
        }
    }


    @OnClick({R.id.tv_register, R.id.tv_forget_password, R.id.bt_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_login:
                beginLogin();
                toastShort("登陆");
                break;
            case R.id.tv_register:
                //toastShort("注册");
                toastShort("页卡演示");
                goNextActivity(MainActivity2.class);
                break;
            case R.id.tv_forget_password:
                toastShort("忘记密码");
                goNextActivity(UpdateUserInfoActivity.class);
                break;
        }
    }

    private void beginLogin() {
        String accountString = etAccount.getText().toString().trim();
        String passwordString = etPassword.getText().toString().trim();
        // TODO: 2018/12/25 验证账号密码合法性
        if (TextUtils.isEmpty(accountString)) {
            toastShort("账号不能为空！");
            return;
        }
        if (TextUtils.isEmpty(passwordString)) {
            toastShort("密码不能为空！");
            return;
        }
        if (cbLoginInfo.isChecked()) {
            //把账号、密码存到sharedPreference
            SharedPreferenceUtil.put(this, "account", accountString);
            SharedPreferenceUtil.put(this, "password", passwordString);
            SharedPreferenceUtil.put(this, "loginInfo", true);

            if (cbAutoLogin.isChecked()) {
                SharedPreferenceUtil.put(this, "autoLogin", true);
            } else {
                SharedPreferenceUtil.put(this, "autoLogin", false);
            }
        } else {
            SharedPreferenceUtil.put(this, "account", null);
            SharedPreferenceUtil.put(this, "password", null);
            SharedPreferenceUtil.put(this, "loginInfo", false);
        }
        doLogin(accountString, passwordString);
    }

    /**
     * 真正的登陆逻辑
     *
     * @param accountString  账号
     * @param passwordString 密码
     */
    private void doLogin(String accountString, String passwordString) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.Login3 requestInterfaceLogin = retrofit.create(RequestInterface.Login3.class);
        Call<ServerResponse<User>> call = requestInterfaceLogin.login(accountString, passwordString);

        call.enqueue(new Callback<ServerResponse<User>>() {

            @Override
            public void onResponse(Call<ServerResponse<User>> call, Response<ServerResponse<User>> response) {
                /**
                 * response.body()获取到返回的ServerResponse，再通过获取Status判断是否
                 * 登陆成功/请求数据成功
                 */
                if (response.body() == null) {
                    toastShort("未获取到相关数据");
                    return;
                }
                //log(response.body().getMsg());
                if (response.body().getStatus() == 0) {
                    //获取返回的数据（就是泛型ServerResponse中的T所代表的数据）
                    User user = response.body().getData();

                    log("");
                    //goNextActivity(MainActivity2.class);
                    //获取当前应用
                   /* MyApp app = (MyApp) getApplication();
                    //把返回的user保存到myAPP中
                    app.setCurrentUser(user);
                    Log.d(TAG, "onResponse: user^^^^^^^^^^" + user.toString());
                    Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();*/
                    //跳转主活动
                    Timer time = new Timer();
                    TimerTask tk = new TimerTask() {
                        Intent intent = new Intent(LoginActivity.this,MainActivity2.class);
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub

                            startActivity(intent);
                            finish();
                        }
                    };time.schedule(tk, 3000);
                    toastShort("登陆成功！");
                    //跳转主活动
                    //Intent intent = new Intent(LoginActivity.this, MainActivity2.class);
                   // startActivity(intent);
                   // finish();
                } else {
                    toastShort("登陆失败");
                }
            }
            @Override
            public void onFailure(Call<ServerResponse<User>> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("登陆失败！");
            }
        });
    }
}
